import React from 'react';
import { computedPosition } from '../../main/heightChangeFit';

export default class FixedView extends React.PureComponent {
    positionIndex = {
        0: 'top',
        1: 'left',
        2: 'right',
        3: 'bottom',
    };

    isNumber = n => {
        if (typeof n === 'number') {
            return true;
        }

        return false;
    };

    handleFixedStyle = (top, left, right, bottom) => {
        if (!this.isNumber(top) && !this.isNumber(left) && !this.isNumber(right) && !this.isNumber(bottom)) return {};
        const style = { position: 'fixed' };
        const positionArray = [top, left, right, bottom];
        positionArray.forEach((item, index) => {
            if (this.isNumber(item)) {
                const key = this.positionIndex[index];
                if (key === 'top' && WPT.os.isFullscreen) {
                    style[key] = computedPosition(item);
                } else {
                    style[key] = `${item}px`;
                }
            }
        });

        return style;
    };

    render() {
        const {
            children, className, top, left, right, bottom, position = {}, ...restProps
        } = this.props;
        const fixdStyle = this.handleFixedStyle(
            this.isNumber(position.top) ? position.top : top,
            this.isNumber(position.left) ? position.left : left,
            this.isNumber(position.right) ? position.right : right,
            this.isNumber(position.bottom) ? position.bottom : bottom
        );

        return (
            <div className={className} {...restProps} style={fixdStyle}>
                {children}
            </div>
        );
    }
}
